package runner

import (
	"context"
	"fmt"
	"os"
	"strings"
	"sync"
)

type Runner struct {
	MaxProcess       int
	ConcurrentNumber int
	Command          string
	BatchCommandFile string
	Pool             *ProcessPool
	sync.WaitGroup
}

func InitRunner(max int, number int, command string, file string, ctx context.Context) *Runner {
	r := &Runner{
		MaxProcess:       max,
		ConcurrentNumber: number,
		Command:          command,
		BatchCommandFile: file,
		Pool:             GetProcessPool(max, ctx),
	}
	return r
}

func (r *Runner) StartCommand() error {
	p, err := GetProcessData(fmt.Sprintf("%d %s", r.ConcurrentNumber, r.Command))
	if err != nil {
		return err
	}
	r.Pool.Do(p, &r.WaitGroup)
	return nil
}

func (r *Runner) StartFile() error {
	b, err := os.ReadFile(r.BatchCommandFile)
	if err != nil {
		return err
	}
	line := strings.Split(string(b), "\n")
	for _, row := range line {
		row = strings.TrimSpace(row)
		p, err := GetProcessData(row)
		if err != nil {
			return err
		}
		r.Pool.Do(p, &r.WaitGroup)
	}
	return nil
}
